package ws

import (
	"trpg-common/logger"
	"trpg-message/entity"
)

// Hub maintains the set of active clients and broadcasts messages to the clients.
type Hub struct {
	// Registered clients.
	clients map[int64]map[*Client]struct{}

	// Inbound messages from the clients.
	broadcast chan entity.Message

	// Register requests from the clients.
	register chan *Client

	// Unregister requests from clients.
	unregister chan *Client
}

func newHub() *Hub {
	return &Hub{
		broadcast:  make(chan entity.Message),
		register:   make(chan *Client),
		unregister: make(chan *Client),
		clients:    make(map[int64]map[*Client]struct{}),
	}
}

func (h *Hub) run() {
	for {
		select {
		case client := <-h.register:
			logger.Logger.Infof("connection register, roomId: %d, uid: %s", client.roomId, client.uid)
			if _, ok := h.clients[client.roomId]; !ok {
				h.clients[client.roomId] = make(map[*Client]struct{})
			}
			h.clients[client.roomId][client] = struct{}{}
		case client := <-h.unregister:
			if _, ok := h.clients[client.roomId][client]; ok {
				delete(h.clients[client.roomId], client)
				close(client.send)
				if len(h.clients[client.roomId]) == 0 {
					delete(h.clients, client.roomId)
				}
			}
		case message := <-h.broadcast:
			logger.Logger.Infof("broadcast message: %+v", message)
			for client := range h.clients[message.RoomId] {
				logger.Logger.Debugf("broadcast to uid:%s", client.uid)
				select {
				case client.send <- message:
				default:
					close(client.send)
					delete(h.clients[message.RoomId], client)
				}
			}
		}
	}
}
